package com.example.esaclient;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

public class LoginActivity extends Activity {

	// Shared Preferences
	private static SharedPreferences mSharedPreferences;
	// Preference Constants
	static final String PREF_ESA_USERNAME = "esa_username";
	static final String PREF_ESA_PWD = "esa_password";
	static final String PREF_ESA_USRID = "esa_userID";
	
	private String savedUser, savedPwd;
	private Boolean isESAOnline = false;
	public String userID = "0";
	private String proxy_server_url;

	private AlertDialogManager alert;
	private ProgressDialog dialog;
	private  EditText txtUser;
	private EditText txtPwd;
	private CheckBox chkSaveUser;
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_screen);
		alert = new AlertDialogManager();

		TextView txtNewAccount;
		txtNewAccount = (TextView) findViewById(R.id.txtNewAccount);
		txtNewAccount.setText(Html.fromHtml("<u><b>Create new Account</b></u>"));

		 txtUser = (EditText) findViewById(R.id.txtUser);
		 txtPwd = (EditText) findViewById(R.id.txtPwd1);
		 chkSaveUser = (CheckBox) findViewById(R.id.chkSaveUser);
		// Shared Preferences
		mSharedPreferences = getApplicationContext().getSharedPreferences(
				"MyPref", 0);
		savedUser = mSharedPreferences.getString(PREF_ESA_USERNAME, "");
		savedPwd = mSharedPreferences.getString(PREF_ESA_PWD, "");
		if (!savedUser.trim().equals("")) {
			txtUser.setText(savedUser);
			txtPwd.setText(savedPwd);
			chkSaveUser.setChecked(true);
		}
		
		proxy_server_url = new GlobalSettings(this).getPrefString(GlobalSettings.PREF_ESA_URL);
		if(proxy_server_url.equals("")){// set the default server
			proxy_server_url="apat.di.uniba.it:8750";
			Editor e = mSharedPreferences.edit();
			e.putString(GlobalSettings.PREF_ESA_URL, proxy_server_url);
			e.commit();
		}
			
		// Checking Esa server availability
		serverStatus(this.getCurrentFocus());

		
	}
	
	
	public void login(View v){
		
				// Checking Esa server availability
				serverStatus(v);
				if (!isESAOnline) {
					alert.showAlertDialog(
							LoginActivity.this,
							"ESA Connection Error",
							"The ESA Server appears to be offline. Please, retry later.",
							false);
					return;
				}

				TextView tvErr;
				tvErr = (TextView) findViewById(R.id.txtMetric3Title);
				tvErr.setVisibility(View.INVISIBLE);

				ProgressBar logProgress;
				logProgress = (ProgressBar) findViewById(R.id.LoginProgress);
				logProgress.setVisibility(View.VISIBLE);

				final String email = txtUser.getText().toString();
				final String pwd = txtPwd.getText().toString();

				if (chkSaveUser.isChecked()) {
					// Shared Preferences
					Editor e = mSharedPreferences.edit();
					e.putString(PREF_ESA_USERNAME, email);
					e.putString(PREF_ESA_PWD, pwd);
					
					e.commit();
				}

				// calling webService
				new LoginToESA().execute(email, pwd, this);

						
	}
	
	
	
	

	public void esaResult(Integer result) {
		//hiding progress circle
		ProgressBar logProgress;
		logProgress = (ProgressBar) findViewById(R.id.LoginProgress);
		logProgress.setVisibility(View.INVISIBLE);

		// result is the returned user ID (0 if not present)
		if (result != 0) {
			
			int oldUsr =  new GlobalSettings(this).getPrefInt(GlobalSettings.PREF_ESA_USRID);
			if(oldUsr!=result){ //user has changed clearing all shared prefs
				
				Editor e = mSharedPreferences.edit();
				e.remove(GlobalSettings.PREF_ESA_USRID);
			     
			     e.remove(GlobalSettings.PREF_KEY_TWITTER_LOGIN);
			     e.remove(GlobalSettings.PREF_KEY_TWITTER_USERNAME);
			     
			     e.remove(GlobalSettings.PREF_KEY_FACEBOOK_LOGIN);
			     e.remove(GlobalSettings.PREF_KEY_FACEBOOK_USERNAME);
			     
			     e.remove(GlobalSettings.PREF_KEY_GOOGLE_LOGIN);
			     e.remove(GlobalSettings.PREF_KEY_GOOGLE_USERNAME );
			     
			     e.commit();
			//saving new userID in shared prefs
			
			e.putInt(PREF_ESA_USRID, result);
			e.commit();
			}
			//opening user timeline
			Intent intent = new Intent(this, TimelineActivity.class);
			startActivity(intent);
		} else {
			TextView tvErr;
			tvErr = (TextView) findViewById(R.id.txtMetric3Title);
			tvErr.setVisibility(View.VISIBLE);
		}
	}

	/** Calling Registration Activity */
	public void CreateAccount(View view) {
		Intent intent = new Intent(this, NewAccountActivity.class);
	//	Intent intent = new Intent(this, TimelineActivity.class);
		startActivity(intent);

	}

	public void serverStatus(View view) {
		//refreshing proxy server address
		proxy_server_url = new GlobalSettings(this).getPrefString(GlobalSettings.PREF_ESA_URL);
		
		ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
		// Check if Internet present
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present

			alert.showAlertDialog(LoginActivity.this,
					"Internet Connection Error",
					"Please connect to working Internet connection", false);
			TextView txtServStatus;
			txtServStatus = (TextView) findViewById(R.id.txtServStatus);
			txtServStatus.setTextColor(Color.RED);
			txtServStatus.setText("Offline ");
			isESAOnline = false;
			// stop executing code by return
			return;
		}

		
		dialog = ProgressDialog.show(LoginActivity.this, "",
				"Contacting Esa Server. Please, wait...", true);
		dialog.show();
		
		
		
		Thread networkThread = new Thread() {
			public void run() {
				try {
					
					try{
						  URI uri = new URI("http://" + proxy_server_url); 
						  String url = uri.getHost();						  
						  int port=uri.getPort();
						  
						  if(port==-1){ //port not specified, using default
							  port=80;
						  }						  
						
				
					// This method will block no more than timeoutMs.
					// If the timeout occurs, SocketTimeoutException is thrown.
					int timeoutMs = 3000; // 3 seconds
					SocketAddress sockaddr = new InetSocketAddress(url,port);
					
					Socket sock = new Socket();
					sock.connect(sockaddr, timeoutMs);
					// Ok, esa server is reachable
					runOnUiThread(new Runnable() {
						public void run() {
							TextView txtServStatus;
							txtServStatus = (TextView) findViewById(R.id.txtServStatus);
							txtServStatus.setTextColor(Color.GREEN);
							txtServStatus.setText("Online ");
						}
					});
					isESAOnline = true;
					}
					catch (URISyntaxException ex){
						Log.e("EsaClient", ex.getMessage());
						// esa server is unreachable
						runOnUiThread(new Runnable() {
							public void run() {
								TextView txtServStatus;
								txtServStatus = (TextView) findViewById(R.id.txtServStatus);
								txtServStatus.setTextColor(Color.RED);
								txtServStatus.setText("Offline ");
							}
						});
						isESAOnline = false;
					}
					

				} catch (Exception e) {
					Log.e("Esa Connection Error", e.getMessage());
					// esa server is unreachable
					runOnUiThread(new Runnable() {
						public void run() {
							TextView txtServStatus;
							txtServStatus = (TextView) findViewById(R.id.txtServStatus);
							txtServStatus.setTextColor(Color.RED);
							txtServStatus.setText("Offline ");
						}
					});
					isESAOnline = false;
				}
				dialog.dismiss();
			}

		};
		networkThread.start();
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	  @Override
      public boolean onOptionsItemSelected(MenuItem item) {
          switch (item.getItemId()) {
              case R.id.mnu_settings:
                      Intent intent = new Intent(this, SettingsActivity.class);
                      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                      startActivity(intent);
                      return true;
              default:
                  return super.onOptionsItemSelected(item);
          }
      }

}